package com.ufo.all.config;


import at.pollux.thymeleaf.shiro.dialect.ShiroDialect;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.LinkedHashMap;
import java.util.Map;


@Configuration
public class MyShiroConfig {


    //3.ShrioFilterFactoryBean 过滤工厂
    @Bean
    public ShiroFilterFactoryBean getShrioFilterFactoryBean(@Qualifier("getDefaultWebSecurityManager") DefaultWebSecurityManager defaultWebSecurityManager) {

        ShiroFilterFactoryBean factoryBean = new ShiroFilterFactoryBean();
        factoryBean.setSecurityManager(defaultWebSecurityManager);
        //添加 Shiro 的内置过滤器=======================
        /*
            anon : 无需认证，就可以访问
            authc : 必须认证，才能访问
            user : 必须拥有 “记住我”功能才能用
            perms : 拥有对某个资源的权限才能访问
            role : 拥有某个角色权限才能访问
         */
        Map<String, String> map = new LinkedHashMap<>();
        // 设置 /user/addUser 这个请求,只有认证过才能访问
//        map.put("/user/addUser","authc");
//        map.put("/user/deleteUser","authc");
        // 设置 /user/ 下面的所有请求,只有认证过才能访问
        map.put("/uu/level1/*", "perms[add:one]");
        map.put("/uu/level2/*", "perms[add:three]");
        map.put("/uu/level3/*", "perms[add:three]");

        map.put("/uu/**", "authc");

        factoryBean.setFilterChainDefinitionMap(map);


        // 设置登录的请求
        factoryBean.setLoginUrl("/toLogin");
        factoryBean.setUnauthorizedUrl("/noauth");
        return factoryBean;
    }

    //2.DafauLtwebSecurityManager 安全管理
    @Bean
    public DefaultWebSecurityManager getDefaultWebSecurityManager(@Qualifier("myRealm") MyRealm myRealm) {

        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
        securityManager.setRealm(myRealm);
        return securityManager;
    }


    //1.创建Realm对象，需要自定义类
    @Bean
    public MyRealm myRealm() {
        return new MyRealm();
    }


    /*整合Thymeleaf和shiro*/
    @Bean
    public ShiroDialect  shiroDialect(){
        return new ShiroDialect();
    }


}
